import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
@Injectable()
export class ClientSocketService {
    private socket: WebSocket;

    constructor() {

    }

    createSocket(path: string): Observable<any> {
        !this.socket && (this.socket = new WebSocket(path));
        return new Observable(ob=>{
            // 建立连接
            this.socket.onopen = (()=>{
                ob.next('init');
                this.socket.send('init');
            });

            // 获取消息
            this.socket.onmessage = ((res)=>{
                ob.next(res);
            });

            // 错误
            this.socket.onerror = ((error)=>{
                ob.error(error);
            });

            // 完成
            this.socket.onclose = (()=>{
                ob.complete();
            });

            // 如果取消订阅关闭当前socket
            return ()=>{
                this.socket.close();
            }

        });
    }

    sendMsg(msg:string):void{
        this.socket && this.socket.send(msg);
    }
}